package task

import (
	"bytes"
	"encoding/json"
	"io"
	"net/http"
	"time"

	"github.com/PuerkitoBio/goquery"
)

type SubmissionTask struct {
	TaskBase
}
type submissionInfo struct {
	SubmissionId string
	When         int64
	Who          string
	Problem      string
	ProblemUrl   string
	Lang         string
	Verdict      string
	Time         string
	Memory       string
	Code         string
}

func (s *SubmissionTask) GetParseFunc(r io.Reader) interface{} {
	doc, err := goquery.NewDocumentFromReader(r)
	if err != nil {
		s.SetErr(err)
		return ""
	}
	submissionQue := make([]submissionInfo, 0, 50)
	trs := doc.Find(".status-frame-datatable").Find("tr")
	for i := 1; i < trs.Length(); i++ {
		temI := submissionInfo{}
		temI.SubmissionId = trim(trs.Eq(i).Find("td").Eq(0).Text())
		ti, _ := time.Parse("Jan/02/2006 15:04", trim(trs.Eq(i).Find(".format-time").Text()))
		temI.When = ti.UnixMilli()
		temI.Who = trim(trs.Eq(i).Find("td").Eq(2).Text())
		temI.Problem = trim(trs.Eq(i).Find("td").Eq(3).Text())
		temI.ProblemUrl = "https://codeforces.com" + trim(trs.Eq(i).Find("td").Eq(3).Find("a").AttrOr("href", ""))
		temI.Lang = trim(trs.Eq(i).Find("td").Eq(4).Text())
		temI.Verdict = trim(trs.Eq(i).Find("td").Eq(5).Text())

		temI.Time = trim(trs.Eq(i).Find("td").Eq(6).Text())
		temI.Memory = trim(trs.Eq(i).Find("td").Eq(7).Text())
		resp, err := http.Post("https://codeforces.com/data/submitSource?submissionId="+temI.SubmissionId, "application/json;charset=utf-8", bytes.NewBuffer([]byte("")))
		if err != nil {
			s.SetErr(err)
		} else {
			jsonData, e := io.ReadAll(resp.Body)
			if e != nil {
				s.SetErr(e)
			} else {
				t := struct {
					Source string `json:"source"`
				}{}
				json.Unmarshal(jsonData, &t)
				temI.Code = t.Source
			}
		}
		submissionQue = append(submissionQue, temI)

	}

	return submissionQue

}

func NewUserSubmissionTask(name string, contestId string) ITask {
	return &SubmissionTask{
		TaskBase{
			url: "https://codeforces.com/submissions/" + name + "/contest/" + contestId,
		},
	}
}
